package com.iweibo.service;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;

import com.iweibo.bean.UserInfo;
import com.iweibo.db.DBConfig.Table;
import com.iweibo.db.DatabaseHelper;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.net.RequestListener;

/**
 * 用户信息业务处理 
 * @author nibo
 * @date 2012-10-15
 *
 */
public class UserInfoService {
	private DatabaseHelper db = null;
	public UserInfoService(Context context) {
		db = new DatabaseHelper(context);
	}
	/**
	 * 添加用户信息
	 * 
	 * @param info
	 *            用户信息对象
	 * @return true:成功<br>
	 *         false:失败
	 */
	public boolean addUser(UserInfo info) {
		//用户信息为空,返回添加失败
		if (null == info) {
			return false;
		}
		String sql = "INSERT INTO " + Table.USER_INFO_NAME + 
						"(USER_ID, USER_NAME, TOKEN, REMIND_IN, EXPIRES_IN, IS_DEFAULT, USER_ICON) values(?, ?, ?, ?, ?, ?, ?)";
		SQLiteDatabase database = null;
		try {
			database = db.getWritableDatabase();
			database.execSQL(sql, new Object[]{info.getUserId(), info.getUserName(), info.getToken(), 
					info.getRemindIn(), info .getExpiresIn(), 0, info.getUserHeadImg()});
		} finally {
			DatabaseHelper.close(database);
		}
		return true;
	}
	
	/**
	 * 查询用户信息根据用户id
	 * @param userId 用户id
	 * @return UserInfo对象
	 */
	public UserInfo queryUserInfoById(long userId) {
		String sql = "SELECT * FROM " + Table.USER_INFO_NAME + " t where t.USER_ID = ?";
		UserInfo info = null;
		SQLiteDatabase database = null;
		Cursor cursor = null;
		Drawable drawable = null;
		ByteArrayInputStream inputStream = null;
		try {
			database = db.getReadableDatabase();
			cursor = database.rawQuery(sql, new String[]{String.valueOf(userId)});
			if (cursor.moveToNext()) {
				info = new UserInfo();
				info.setId(cursor.getLong(cursor.getColumnIndex("_id")));
				info.setUserId(cursor.getLong(cursor.getColumnIndex("USER_ID")));
				info.setUserName(cursor.getString(cursor.getColumnIndex("USER_NAME")));
				info.setToken(cursor.getString(cursor.getColumnIndex("TOKEN")));
				info.setRemindIn(cursor.getInt(cursor.getColumnIndex("REMIND_IN")));
				info.setExpiresIn(cursor.getInt(cursor.getColumnIndex("EXPIRES_IN")));
				info.setIsDefault(cursor.getInt(cursor.getColumnIndex("IS_DEFAULT")));
				byte[] iconByte = cursor.getBlob(cursor.getColumnIndex("USER_ICON"));
				if (null != iconByte) {
					inputStream = new ByteArrayInputStream(iconByte);
					drawable = Drawable.createFromStream(inputStream, "image_header");
				}
				info.setUserIcon(drawable);
			}
		} finally {
			DatabaseHelper.close(cursor, database);
		}
		return info;
	}
	
	/**
	 * 修改用户信息根据用户id
	 * 
	 * @param info
	 *            用户信息
	 * @return true:成功<br>
	 *         false:失败
	 */
	public boolean updateUserInfoById(UserInfo info) {
		//用户信息为空或者用户id为空直接返回修改失败
		if (null == info || 0 == info.getUserId()) {
			return false;
		}
		String sql = "UPDATE " + Table.USER_INFO_NAME + " SET TOKEN = ?, REMIND_IN = ?, EXPIRES_IN = ?, IS_DEFAULT = ?, USER_ICON = ? WHERE USER_ID = ?";
		SQLiteDatabase database = null;
		try {
			database = db.getWritableDatabase();
			database.execSQL(sql, new Object[]{info.getToken(), info.getRemindIn(), 
					info.getExpiresIn(), info.getIsDefault(), info.getUserHeadImg(), info.getUserId()});
		} finally {
			DatabaseHelper.close(database);
		}
		return true;
	}
	
	/**
	 * 查询所有的用户信息
	 * @return 用户信息集合
	 */
	public List<UserInfo> findAllUserInfo() {
		String sql = "SELECT * FROM " + Table.USER_INFO_NAME;
		ArrayList<UserInfo> listUsers = null;
		SQLiteDatabase database = null;
		Cursor cursor = null;
		try {
			database = db.getReadableDatabase();
			cursor = database.rawQuery(sql, null);
			UserInfo info = null;
			Drawable drawable = null;
			ByteArrayInputStream inputStream = null;
			listUsers = new ArrayList<UserInfo>(cursor.getCount());
			while (cursor.moveToNext()) {
				info = new UserInfo();
				info.setId(cursor.getLong(cursor.getColumnIndex("_id")));
				info.setUserId(cursor.getLong(cursor.getColumnIndex("USER_ID")));
				info.setUserName(cursor.getString(cursor.getColumnIndex("USER_NAME")));
				info.setToken(cursor.getString(cursor.getColumnIndex("TOKEN")));
				info.setRemindIn(cursor.getInt(cursor.getColumnIndex("REMIND_IN")));
				info.setExpiresIn(cursor.getInt(cursor.getColumnIndex("EXPIRES_IN")));
				info.setIsDefault(cursor.getInt(cursor.getColumnIndex("IS_DEFAULT")));
				byte[] iconByte = cursor.getBlob(cursor.getColumnIndex("USER_ICON"));
				if (null != iconByte) {
					inputStream = new ByteArrayInputStream(iconByte);
					drawable = Drawable.createFromStream(inputStream, "image_header");
				}
				info.setUserIcon(drawable);
				listUsers.add(info);
			}
			return listUsers;
		} finally {
			DatabaseHelper.close(cursor, database);
		}
	}
	
	public void getWeiboUserInfo(String token, String expiresIn, long uid, RequestListener listener) {
		Oauth2AccessToken accessToken = new Oauth2AccessToken(token, expiresIn);
		UsersAPI usersAPI = new UsersAPI(accessToken);
		usersAPI.show(uid, listener);
	}
}
